import { stringify } from 'qs';
import RNFS from 'react-native-fs';
import { DeviceEventEmitter } from 'react-native';
import request from '../utils/request';
import { ipConfig } from './config';
import myBadge from '../utils/plugins/my-badge';
import { UtilToast } from '../utils/util-method';

// 系统管理 获取APP信息
const modelPath = '/api-ms/system/SysAppReleaseinfo/';

const getProgress = res => Math.round((res.bytesWritten / res.contentLength) * 100);
const downloadDest = `${RNFS.ExternalDirectoryPath}/SmartFactory.apk`;

const downloadRoot = 'http://proxy.pea.cs2025.cn';

// 根据APPID查询最新版本
export const findLatestVersion = async params => request(`${ipConfig.url(modelPath)}/findVersion?${stringify(params)}`);

export const downloadApp = async (param) => {
  let tPro = 0;
  const formUrl = `${ipConfig.rootURL}${param}`;
  // console.error(formUrl);
  // const formUrl = `${downloadRoot}${param}`;
  // const formUrl = 'http://192.168.15.204:7001/upload/file/ITSMOB3_SDHK.apk';
  const progress = res => {
    const tmPro = getProgress(res);
    if ((tmPro - tPro) > 8) {
      tPro = tmPro;
      const pro = getProgress(res);
      // dispatch(createAction('version/updateVersion')({ progress: `${pro}%` }));
      DeviceEventEmitter.emit('updateProgressEvent', `${pro}%`);
    }
  };
  const options = {
    fromUrl: formUrl,
    toFile: downloadDest,
    background: true,
    begin: res => {
      console.log('begin', res);
      console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
    },
    progress,
  };

  try {
    const response = await RNFS.downloadFile(options).promise;
    if (response.statusCode !== 200) {
      throw new Error('更新失败，下载地址异常');
    }
    // global.navigation.goBack();
    DeviceEventEmitter.emit('closeProgressEvent');
    myBadge.installApk(downloadDest);
  } catch (error) {
    catchRrror(error);
  }
};

const catchRrror = (error) => {
  console.error('error', error);
  // global.navigation.goBack();
  DeviceEventEmitter.emit('closeProgressEvent');
  UtilToast('error.message', 'danger');
  // Toast.show({
  //   text: error.message,
  //   duration: 3000,
  //   position: 'bottom',
  // });
};
